#####################################################################
#                                                                   #
#  THIS IS A SOURCE CODE FILE FROM A PROGRAM TO INTERACT WITH THE   #
# LBRY PROTOCOL ( lbry.com ). IT WILL USE THE LBRY SDK ( lbrynet )  #
# FROM THEIR REPOSITORY ( https://github.com/lbryio/lbry-sdk )      #
# WHICH I GONNA PRESENT TO YOU AS A BINARY. SINCE I DID NOT DEVELOP #
# IT AND I'M LAZY TO INTEGRATE IN A MORE SMART WAY. THE SOURCE CODE #
# OF THE SDK IS AVAILABLE IN THE REPOSITORY MENTIONED ABOVE.        #
#                                                                   #
#      ALL THE CODE IN THIS REPOSITORY INCLUDING THIS FILE IS       #
# (C) J.Y.Amihud and Other Contributors 2021. EXCEPT THE LBRY SDK.  #
# YOU CAN USE THIS FILE AND ANY OTHER FILE IN THIS REPOSITORY UNDER #
# THE TERMS OF GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER    #
# VERSION. TO FIND THE FULL TEXT OF THE LICENSE GO TO THE GNU.ORG   #
# WEBSITE AT ( https://www.gnu.org/licenses/gpl-3.0.html ).         #
#                                                                   #
# THE LBRY SDK IS UNFORTUNATELY UNDER THE MIT LICENSE. IF YOU ARE   #
# NOT INTENDING TO USE MY CODE AND JUST THE SDK. YOU CAN FIND IT ON #
# THEIR OFFICIAL REPOSITORY ABOVE. THEIR LICENSE CHOICE DOES NOT    #
# SPREAD ONTO THIS PROJECT. DON'T GET A FALSE ASSUMPTION THAT SINCE #
# THEY USE A PUSH-OVER LICENSE, I GONNA DO THE SAME. I'M NOT.       #
#                                                                   #
# THE LICENSE CHOSEN FOR THIS PROJECT WILL PROTECT THE 4 ESSENTIAL  #
# FREEDOMS OF THE USER FURTHER, BY NOT ALLOWING ANY WHO TO CHANGE   #
# THE LICENSE AT WILL. SO NO PROPRIETARY SOFTWARE DEVELOPER COULD   #
# TAKE THIS CODE AND MAKE THEIR USER-SUBJUGATING SOFTWARE FROM IT.  #
#                                                                   #
#####################################################################

# This file will perform a simple search on the LBRY network.

from subprocess import *
import json

from flbry import url
from flbry import following
from flbry import wallet
from flbry import markdown
from flbry import publish
from flbry.variables import *

def simple(args=""):

    
    
    # The user might write the search argument right in the same
    # line as the work search.
    #
    # : channel blenderdumbass
    #
    # Or they can type nothing. And be confused of what happened.
    # So I want to provide a catcher here. If they type nothing it
    # will ask them to provide a search query.

    if not args:
        args = input(" Channel url :: ")
    if not args.startswith("@") and not args.startswith("lbry://@"):
        args = "@"+args
        
    # So we want to request a query to the SDK to search what ever
    # the user wants. The problem is it can be a very large output.
    # For example the "blender dumbass" query returns 1000 claims
    # on the LBRY network. And people will wait for a very long time
    # on something that might have a million claims.

    # So instead we are going to request only the first 20 and let
    # the user load more.

    w, h = tsize()
    
    page_size = h - 5
    page = 1
    
    while True:

        # Printing the search query and page number
        center("CHANNEL: "+args+" PAGE:"+str(page))

       
        out = check_output(["flbry/lbrynet",
                         "claim", "search", '--channel='+args,
                         '--page='+str(page),
                         '--page_size='+str(page_size),
                            "--no_totals",
                            '--order_by=release_time'])

        # Now we want to parse the json
        
        try:
            out = json.loads(out)
        except:
            print("   Connect to LBRY first.")
            return

        
        
        try:

            data_print = {"categories":["Type", "Title"],
                          "size":[1,5],
                          "data":[]}

            # List what we found
            for n, i in enumerate(out["items"]):
                
                title = "---!Failed Loading Title---"
                ftype = "claim"
                
                try:
                    try:
                        title = i["value"]["title"]
                    except:
                        title = i['name']
                        
                    try:
                        ftype = what[i["value"]["stream_type"]]
                    except:
                        ftype = what[i["value_type"]]
                except:
                    pass
            
                
                data_print["data"].append([ftype, title])

            table(data_print)
            # Tell the user that he might want to load more
            center("---type 'more' to load more---")
            page = page +1
            
        # Error messages    
        except Exception as e:
            if "code" in out:
                print("    Error code: ", out["code"]  )
                if out["code"] == -32500:
                    print("   SDK is still starting. Patience!")
            else:
                print("    Error :", e)
            return

        channel_commands = [
            "rss",
            "follow",
            "unfollow",
            "more",
            "support",
            "tip"
        ]

        complete(channel_commands)

        # Making sure that we stop every time a new page is reached
        while True:
            c =  input(typing_dots())

            if c == "rss":
                rss = out["items"][0]["signing_channel"]["short_url"]
                rss = rss.replace("#", ":")
                rss = rss.split("lbry://", 1)[1]

                print("   https://odysee.com/$/rss/"+rss)

            elif c == "follow":
                channel = out["items"][0]["signing_channel"]["permanent_url"]
                try:
                    name = out["items"][0]["signing_channel"]["value"]["title"]
                except:
                    name = out["items"][0]["signing_channel"]["normalized_name"]

                following.follow_channel(channel, name)

            elif c == "unfollow":
                channel = out["items"][0]["signing_channel"]["permanent_url"]
                try:
                    name = out["items"][0]["signing_channel"]["value"]["title"]
                except:
                    name = out["items"][0]["signing_channel"]["normalized_name"]

                following.unfollow_channel(channel, name)

            elif c == "support":
                wallet.support(out["items"][0]["signing_channel"]["claim_id"])

            elif c == "tip":
                wallet.support(out["items"][0]["signing_channel"]["claim_id"], True)

            else:
                break

            complete(channel_commands)

        if c != "more":
            break

    try:
        c = int(c)
    except:
        return

    while True:
        url.get(out["items"][c]["canonical_url"])
        c =  input(typing_dots())
        if not c:
            break
        try:
            c = int(c)
        except:
            return

def select(message="", claim_id=False, anonymous=False):

    # This fucntion will give users to select one of their channels.
    center(message)

    out = check_output(["flbry/lbrynet",
                         "channel", "list"])

    # Now we want to parse the json

    try:
        out = json.loads(out)
    except:
        print("   Connect to LBRY first.")
        return

    d = {"categories":["lbry url", "title"],
         "size":[1,2],
         "data":[]}

    for n, i in enumerate(out["items"]):
        name = "[no name]"
        title = "[no title]"
        try:
            name = i["name"]
            title = i["value"]["title"]
        except:
            pass
        
        d["data"].append([name, title])


    if anonymous:
       d["data"].append(["[anonymous]", "[no title]"])
    table(d)
    center("select a channel by typing it's number")
        
    select = input(typing_dots())
    try:
        select = int(select)
        if select > len(out["items"])-1 and anonymous:
            if claim_id:
                return None, None
            return None
        if claim_id:
            return out["items"][select]["name"], out["items"][select]["claim_id"]
        return out["items"][select]["name"]
    except:
        raise()
        if claim_id:
            return out["items"][0]["name"], out["items"][0]["claim_id"]
        return out["items"][0]["name"]

def create():
    # The dictionaries for the data table
    d = {"categories": ["Name", "Bid", "Title", "Description"],
                        "size": [2,1,3,6],
                        "data": []}
    d2 = {"categories": ["Email", "Website URL"],
                         "size": [1,1],
                         "data": []}
    d3 = {"categories": ["Thumbnail URL", "Cover URL"],
                         "size": [1,1],
                         "data": []}
    d_tags = {"categories": [],
            "size": [],
            "data": [[]]}
    d_langs = {"categories": [],
            "size": [],
            "data": [[]]}

    # Put some default values so the table looks nice
    # They have their own variables so we can check against them later
    bid = 0.0001
    default_title = "[no title]"
    default_description = "[no description]"
    default_email = "[no email]"
    default_web_url = "[no website]"
    default_thumb_url = "[no thumbnail]"
    default_cover_url = "[no cover image]"
    default_tags = ["[no tags]"]
    default_langs = ["[no languages]"]

    title = default_title
    description = default_description
    email = default_email
    web_url = default_web_url
    thumb_url = default_thumb_url
    cover_url = default_cover_url
    tags = default_tags
    langs = default_langs

    name = input("   Name: ")
    if not name.startswith("@"):
        name = "@" + name

    complete([
        "name",
        "bid",
        "title",
        "description",
        "email",
        "website",
        "thumbnail",
        "cover",
        "tags",
        "languages",
        "help",
        "create"
    ])

    while True:
        # Just setting the "data" list wasn't working, so clear it then append to it
        d["data"] = []
        d2["data"] = []
        d3["data"] = []
        d["data"].append([name, str(bid), title, description])
        d2["data"].append([email, web_url])
        d3["data"].append([thumb_url, cover_url])

        d_tags["categories"] = []
        d_tags["size"] = []
        d_tags["data"] = [[]]
        for tag in tags:
            d_tags["categories"].append(" ")
            d_tags["size"].append(1)
            d_tags["data"][0].append(tag)

        d_langs["categories"] = []
        d_langs["size"] = []
        d_langs["data"] = [[]]
        for lang in langs:
            d_langs["categories"].append(" ")
            d_langs["size"].append(1)
            d_langs["data"][0].append(lang)

        table(d, False)
        table(d2, False)
        table(d3, False)
        table(d_tags, False)
        table(d_langs, False)
        center("--- for commands type 'help' ---")

        c = input(typing_dots())
        if not c:
            return

        if c == "name":
            name = input("   Name: ")
            if not name.startswith("@"):
                name = "@" + name

        elif c == "bid":
            while True:
                bid = input("   Bid: ")
                try:
                    float(bid)
                    break
                except:
                    center("Bid is not a number, try again", "bdrd")
                    bid = ""

        elif c == "title":
            title = input("   Title: ")

        elif c.startswith("description"):
            c = c + ' '
            a = c[c.find(" "):]
            if len(a) > 1:
                description = file_or_editor(a, "Type the description here. Don't forget to save. Then return to FastLBRY.")
            else:
                description = input("   Description: ")

        elif c == "email":
            email = input("   Email: ")

        elif c == "website":
            web_url = input("   Website URL: ")

        elif c == "thumbnail":
            thumb_url = input("   Thumbnail URL: ")
            # Try to upload
            thumb_url = publish.speech_upload(thumb_url)

        elif c == "cover":
            cover_url = input("   Cover URL: ")
            # Try to upload
            cover_url = publish.speech_upload(cover_url)

        elif c == "tags":
            tags = input("   Enter the tags for the channel, separated by commas: ")
            tags = tags.split(",")
            for tag in tags:
                tag.strip()

        elif c == "languages":
            langs = input("   Enter the languages for the channel, separated by commas: ")
            langs = langs.split(",")
            for lang in langs:
                lang.strip()

        elif c == "help":
            markdown.draw("help/create-channel.md", "Create Channel Help")

        elif c == "create":
            command = ["flbry/lbrynet", "channel", "create", "--name="+name, "--bid="+str(bid)]

            if title != default_title:
                command.append("--title="+title)

            if description != default_description:
                command.append("--description="+description)

            if email != default_email:
                command.append("--email="+email)

            if web_url != default_web_url:
                command.append("--website_url="+web_url)

            if thumb_url != default_thumb_url:
                command.append("--thumbnail_url="+thumb_url)

            if cover_url != default_cover_url:
                command.append("--cover_url="+cover_url)

            if tags != default_tags:
                for tag in tags:
                    command.append("--tags="+tag)

            if langs != default_langs:
                for lang in langs:
                    command.append("--languages="+lang)

            out = check_output(command)
            out = json.loads(out)

            if "message" in out:
                center("Error creating channel: "+out["message"], "bdrd")
            else:
                center("Successfully created "+name, "bdgr")

            return
